"""" 
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License.
"""
from copy import copy
from logging import getLogger

import zope.interface

from lxml import etree

from meercat.base.metadata import Metadata
from meercat.interfaces import IMetadata
from meercat.mapreduce import interfaces
from meercat.mapreduce.exceptions import *



log = getLogger('meercat.mapreduce.reducers.xml')

class XmlReducer(object):
    zope.interface.implements(interfaces.IReducer)
    
    def __init__(self, formats, root, xpath):
        log.debug('XmlReducer(formats=%s, root=%s, xpath=%s)' % (str(formats),
                                                                 str(root),
                                                                 str(xpath)))
        self.formats = formats
        self.root = root
        self.xpath = xpath
    
    def getFormats(self):
        """ Return an iterable of the formats that can be reduced by this
        reducer """
        return self.formats
    
    def reduce(self, *metadata):
        log.debug('%s.reduce(%s)' % (str(self),str(metadata)))
        root = etree.Element(self.root)
        
        for m in metadata:
            m = etree.fromstring(m.getValue())
            for node in m.xpath(self.xpath):
                root.append(node)
        
        output_value = etree.tostring(root,encoding='utf-8').replace('\n','').strip()
        
        return Metadata(source=u'XmlReducer',
                        format=self.formats[0],
                        value=output_value)